import axios from 'axios'
import { useUserStore } from '@/store'
import { ElMessage } from 'element-plus'
import { type ResultData } from '@/types/http'
import { ResultEnum } from '@/enums/api/result.enum'
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 5 * 1000,
})

// requset interceptors
service.interceptors.request.use(
  (config) => {
    // 在拦截器内部动态获取 store 实例
    const { token } = useUserStore()
    // const token = userStore.getToken
    // 自动添加 X-token 请求头
    if (token.value) {
      config.headers['X-token'] = token.value
    }
    return config
  },
  (error) => {
    console.log(error)

    return Promise.reject(error.message)
  },
)

// reponse interceptors
service.interceptors.response.use(
  (response) => {
    // 目前的模式是后端统一statusCode 为200
    const res = response.data

    switch (res.code) {
      case ResultEnum.SUCCESS:
        return res.data
      case ResultEnum.BADREQUEST:
        ElMessage.error('参数异常')
        break
      case ResultEnum.UNAUTHORIZED:
        ElMessage.error('登录已过期，请重新登录')
        // 可以添加登录跳转逻辑
        break
      case ResultEnum.FORBIDDEN:
        ElMessage.error('权限不足')
        break
      case ResultEnum.NOTFOUND:
        ElMessage.error('请求的资源不存在')
        break
      case ResultEnum.INTERNALSERVERERROR:
        ElMessage.error('服务器内部错误')
        break
      default:
        ElMessage.error(res.message || '请求失败')
    }
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  (error) => {
    // 非 2xx 状态码处理 401、403、500 等
    ElMessage.error('服务器异常')
    return Promise.reject(error)
  },
)

/**
 * @description 常用请求方法封装
 */
export function get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  return service.get(url, { params, ..._object })
}
export function post<T>(
  url: string,
  params?: object | string,
  _object = {},
): Promise<ResultData<T>> {
  return service.post(url, params, _object)
}
export function put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
  return service.put(url, params, _object)
}
export function remove<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
  return service.delete(url, { params, ..._object })
}

export function download(url: string, params?: object, _object = {}): Promise<BlobPart> {
  return service.post(url, params, { ..._object, responseType: 'blob' })
}

export default service
